<template>
  <!-- 需要设置改div的宽度和长度才能显示 -->
  <div
    :id="'main-' + randomNumber"
    class="main"
    :style="{ width: width, height: height }"
  ></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    xData: {
      type: Array,
      default: () => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    buyPageData: {
      type: Array,
      default: () => [120, 132, 101, 134, 90, 230, 210],
    },
    basicData: {
      type: Array,
      default: () => [220, 182, 191, 234, 290, 330, 310],
    },
    buyPageName: {
      type: String,
      default: "buyPageName",
    },
    basicName: {
      type: String,
      default: "basicName",
    },
  },
  data() {
    return {
      chart: null,
      randomNumber: new Date().getTime() + Math.random(0, 1) * 1000,
    };
  },
  mounted() {
    this.initEcharts();
  },
  methods: {
    initEcharts() {
      this.chart = echarts.init(
        document.getElementById(`main-${this.randomNumber}`)
      );
      // 指定图表的配置项和数据
      var option = {
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.xData,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: this.buyPageName,
            type: "line",
            stack: "Total",
            data: this.buyPageData,
            smooth: true,
          },
          {
            name: this.basicName,
            type: "line",
            stack: "Total",
            data: this.basicData,
            smooth: true,
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      this.chart.setOption(option);
      this.$nextTick(() => {
        this.chart.resize();
      });
      window.addEventListener("resize", () => {
        this.resize();
      });
    },
    resize() {
      this.chart.resize();
    },
  },
  beforeDestory() {
    window.removeEventListener("resize", () => {
      this.resize();
    });
  },
  beforeRouteLeave(to, from, next) {
    window.removeEventListener("resize", () => {
      this.resize();
    });
    next();
  },
};
</script>

<style></style>
